#include "template_manager.hpp"
#include <fstream>
#include <sstream>
#include <filesystem>

namespace fs = std::filesystem;

TemplateManager& TemplateManager::getInstance() {
    static TemplateManager instance;
    return instance;
}

std::string TemplateManager::render(const std::string& template_name, 
                                  const std::map<std::string, std::string>& data) {
    std::string content = readTemplate(template_name);
    content = processTemplate(content, data);
    
    if (!layout_template_.empty()) {
        std::map<std::string, std::string> layout_data = data;
        layout_data["content"] = content;
        content = processTemplate(layout_template_, layout_data);
    }
    
    return content;
}

void TemplateManager::setLayout(const std::string& layout_name) {
    layout_template_ = readTemplate(layout_name);
}

std::string TemplateManager::readTemplate(const std::string& template_name) {
    std::string template_path = template_dir_ + "/" + template_name;
    std::ifstream file(template_path);
    if (!file.is_open()) {
        throw std::runtime_error("Template file not found: " + template_path);
    }
    
    std::stringstream buffer;
    buffer << file.rdbuf();
    return buffer.str();
}

std::string TemplateManager::processTemplate(const std::string& template_content,
                                          const std::map<std::string, std::string>& data) {
    std::string result = template_content;
    for (const auto& [key, value] : data) {
        std::string placeholder = "{{" + key + "}}";
        size_t pos = 0;
        while ((pos = result.find(placeholder, pos)) != std::string::npos) {
            result.replace(pos, placeholder.length(), value);
            pos += value.length();
        }
    }
    return result;
} 